package com.glela.controller;

import com.alibaba.fastjson.JSONObject;
import com.glela.common.constant.ClientType;
import com.glela.common.constant.CommonConstants;
import com.glela.common.util.Config;
import com.glela.common.util.HttpUtil;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.BaseRestrictions;
import com.glela.platform.model.request.RequestUserModel;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.model.response.ResponseUnDefinedUserVo;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.platform.service.UndefinedUserService;
import com.glela.platform.util.ParameterUtils;
import com.glela.platform.vo.WeChatMiniProgramToken;
import com.glela.platform.vo.WeChatTokenVo;
import com.glela.platform.vo.WeChatUserInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
@Controller
@RequestMapping(value = "/undefinedUser")
public class UndefinedUserController extends BaseController {

	private static Logger logger = LoggerFactory.getLogger(UserController.class);
	
	@Autowired
	private UndefinedUserService undefinedUserService;
	
	@Autowired
	private BaseRestrictionsService	baseRestrictionsService;
	
	
	
	/**
	 * H5生成用户信息
	 * 
	 * @param requestUserSet
	 * @returns
	 */
	@ResponseBody
	@RequestMapping(value = "/getUndefinedUserByUndefinedId", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getUndefinedUserByUndefinedId(@RequestBody RequestUserModel requestUserModel,HttpServletRequest request) {
		try {
			if (ParameterUtils.validParams(requestUserModel.getUndefinedId(), requestUserModel.getNickName(),
					requestUserModel.getUrlHeader())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			String clientType = ClientType.APP;
			if(request.getHeader("phoneType") != null && request.getHeader("phoneType").length() > 0) {
				if(request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_IOS) || request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_ANDROID)){
					//user.setUserMachineCode(request.getHeader("machineCode")==null?"":request.getHeader("machineCode"));
					clientType = ClientType.APP;
				} else if(request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_h5) || request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_WX)) {
					clientType = ClientType.H5;
				}
				
			}
			
			return undefinedUserService.getUndefinedUserByUndefinedId(requestUserModel.getUndefinedId(), requestUserModel.getNickName(),requestUserModel.getUrlHeader(),clientType);
			
		} catch (Exception e) {
			logger.error("添加第三方登录信息异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/**
	 *绑定手机号码
	 * 
	 * @param requestUserSet
	 * @returns
	 */
	@ResponseBody
	@RequestMapping(value = "/getUndefinedUserAdd", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getUndefinedUserAdd(@RequestBody RequestUserModel requestUserModel,HttpServletRequest request) {
			if (ParameterUtils.validParams(requestUserModel.getMobile(), requestUserModel.getUndefinedId(),
					requestUserModel.getValidCode())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			
			BaseRestrictions _close_reg_switch = baseRestrictionsService.getBaseRestrictionsForCache("close_reg_switch");
			if(_close_reg_switch != null && StringUtils.isNotBlank(_close_reg_switch.getName())) {
				return new ResponseEntity<>(new ResponseBaseModel(21885, _close_reg_switch.getName()), HttpStatus.OK);
			}
			
			String clientType = ClientType.APP;
			if(request.getHeader("phoneType") != null && request.getHeader("phoneType").length() > 0) {
				if(request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_IOS) || request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_ANDROID)){
					//user.setUserMachineCode(request.getHeader("machineCode")==null?"":request.getHeader("machineCode"));
					clientType = ClientType.APP;
				} else if(request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_h5) || request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_WX)) {
					clientType = ClientType.H5;
				}
				
			}
			
			return undefinedUserService.getUndefinedUserAdd(requestUserModel.getMobile(), requestUserModel.getUndefinedId(),
					requestUserModel.getValidCode(),requestUserModel.getPassword(),requestUserModel.getUndefinedType(),
					requestUserModel.getStoreUserName(),requestUserModel.getRegSource(),requestUserModel.getDeviceCode(),clientType,requestUserModel.getTalentId());
		
	}
	
	/**
	 * APP第三方登录
	 * 
	 * @param requestUserSet
	 * @returns
	 */
	@ResponseBody
	@RequestMapping(value = "/appUndefinedUserAdd", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> appUndefinedUserAdd(@RequestBody RequestUserModel requestUserModel,HttpServletRequest request) {
		if (ParameterUtils.validParams(requestUserModel.getCode())) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
		}
		
		String clientType = ClientType.APP;
		if(request.getHeader("phoneType") != null && request.getHeader("phoneType").length() > 0) {
			if(request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_IOS) || request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_ANDROID)){
				//user.setUserMachineCode(request.getHeader("machineCode")==null?"":request.getHeader("machineCode"));
				clientType = ClientType.APP;
			} else if(request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_h5) || request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_WX)) {
				clientType = ClientType.H5;
			}
			
		}
		
		return undefinedUserService.appUndefinedUserAdd(requestUserModel.getCode(),clientType);
	}
	
	/**
	 * 获得分享accessToken
	 * @param appid
	 * @param secret
	 * @return
	 * @throws IOException	
	 */
//	public static WeChatTokenVo getAccessToken(String appid ,String secret) throws IOException{
//		StringBuffer URL = new StringBuffer() ;
//		URL.append("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=")
//			.append(appid).append("&secret=").append(secret);
//		String json = HttpUtil.doGet(URL.toString()) ;
//		WeChatTokenVo vo = JSONObject.parseObject(json, WeChatTokenVo.class);
//		return vo ;
//	}
	/**
	 *  获得分享accessToken
	 * 
	 * @param requestUserSet
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getAccessToken", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getAccessToken(@RequestBody RequestUserModel requestUserModel) {
		try {
			if (requestUserModel.getAppid()==null||requestUserModel.getSecret()==null) {
				//必传参数未传
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK); 
			}
			StringBuffer URL = new StringBuffer() ;
			URL.append("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=")
			.append(requestUserModel.getAppid()).append("&secret=").append(requestUserModel.getSecret());
		String json = HttpUtil.doGet(URL.toString()) ;
		WeChatTokenVo vo = JSONObject.parseObject(json, WeChatTokenVo.class);
		return new ResponseEntity<>(new ResponseResultModel<WeChatTokenVo>(vo), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("获得分享accessToken异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	/**
	 * 微信授权   通过code换取网页授权access_token
	 * @param appid
	 * @param secret
	 * @param code
	 * @return
	 */
//	public static WeChatTokenVo getWeChaAuthority(String appid , String secret ,String code ) throws IOException{
//		StringBuffer URL = new StringBuffer() ;
//		URL.append("https://api.weixin.qq.com/sns/oauth2/access_token?appid=")
//			.append(appid).append("&secret=").append(secret)
//			.append("&code=").append(code)
//			.append("&grant_type=authorization_code");
//		String json = HttpUtil.doGet(URL.toString()) ;
//		WeChatTokenVo vo = JSONObject.parseObject(json, WeChatTokenVo.class);
//		return vo ;
//	}
	/**
	 *  微信授权   通过code换取网页授权access_token
	 * 
	 * @param requestUserSet
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getWeChaAuthority", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getWeChaAuthority(@RequestBody RequestUserModel requestUserModel) {
		try {
			if (requestUserModel.getCode()==null) {
				//必传参数未传
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK); 
			}
			StringBuffer URL = new StringBuffer();
			URL.append("https://api.weixin.qq.com/sns/oauth2/access_token?appid=")
				.append("wx355d885b16049de1").append("&secret=").append("bf67cd68b84ef5eb0fabe12361e7eb5e")
				.append("&code=").append(requestUserModel.getCode())
				.append("&grant_type=authorization_code");
			String json = HttpUtil.doGet(URL.toString()) ;
			WeChatTokenVo vo = JSONObject.parseObject(json, WeChatTokenVo.class);
		return new ResponseEntity<>(new ResponseResultModel<WeChatTokenVo>(vo), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("通过code换取网页授权access_token异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	/**
	 * 刷新access_token
	 * @param appid
	 * @param refresh_token
	 * @return
	 * @throws IOException 
	 */
//	public static WeChatTokenVo getRefreshToken(String appid , String refreshToken ) throws IOException{
//		StringBuffer URL = new StringBuffer() ;
//		URL.append("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=")
//			.append(appid).append("&grant_type=").append(refreshToken)
//			.append("&refresh_token=REFRESH_TOKEN");
//		String json = HttpUtil.doGet(URL.toString()) ;
//		WeChatTokenVo vo = JSONObject.parseObject(json, WeChatTokenVo.class);
//		return vo ;
//	}
	/**
	 *  刷新
	 * 
	 * @param requestUserSet
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getRefreshToken", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getRefreshToken(@RequestBody RequestUserModel requestUserModel) {
		try {
			if (requestUserModel.getAccessToken()==null||requestUserModel.getOpenId()==null) {
				//必传参数未传
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK); 
			}
			StringBuffer URL = new StringBuffer() ;
			URL.append("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=")
				.append(requestUserModel.getAppid()).append("&grant_type=").append(requestUserModel.getAccessToken())
				.append("&refresh_token=REFRESH_TOKEN");
			String json = HttpUtil.doGet(URL.toString()) ;
			WeChatTokenVo vo = JSONObject.parseObject(json, WeChatTokenVo.class);
		return new ResponseEntity<>(new ResponseResultModel<WeChatTokenVo>(vo), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("刷新异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	
	/**
	 * 拉取用户信息(需scope为 snsapi_userinfo)
	 * @param accessToken   网页授权接口调用凭证
	 * @param openid    微信用户唯一id
	 * @return
	 * @throws IOException
	 */
//	public static WeChatUserInfoVo getUserInfo(String accessToken , String openId ) throws IOException{
//		StringBuffer URL = new StringBuffer() ;
//		URL.append("https://api.weixin.qq.com/sns/userinfo?access_token=")
//			.append(accessToken).append("&openid=").append(openId)
//			.append("&lang=zh_CN");
//		String json = HttpUtil.doGet(URL.toString()) ;
//		WeChatUserInfoVo vo = JSONObject.parseObject(json, WeChatUserInfoVo.class);
//		return vo ;
//	}
	
	/**
	 *  拉取用户信息
	 * 
	 * @param requestUserSet
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getUserInfo", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getUserInfo(@RequestBody RequestUserModel requestUserModel) {
		try {
			if (requestUserModel.getAccessToken()==null||requestUserModel.getOpenId()==null) {
				//必传参数未传
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK); 
			}
			StringBuffer URL = new StringBuffer() ;
			URL.append("https://api.weixin.qq.com/sns/userinfo?access_token=")
				.append(requestUserModel.getAccessToken()).append("&openid=").append(requestUserModel.getOpenId())
				.append("&lang=zh_CN");
			String json = HttpUtil.doGet(URL.toString()) ;
			WeChatUserInfoVo vo = JSONObject.parseObject(json, WeChatUserInfoVo.class);
		return new ResponseEntity<>(new ResponseResultModel<WeChatUserInfoVo>(vo), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("通过code换取网页授权access_token异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/**
	 *  验证
	 * 
	 * @param requestUserSet
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/verificationCode", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> verificationCode(@RequestBody RequestUserModel requestUserModel) {
		try {
			if (requestUserModel.getAccessToken()==null||requestUserModel.getOpenId()==null) {
				//必传参数未传
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK); 
			}
			StringBuffer URL = new StringBuffer();
			URL.append("https://api.weixin.qq.com/sns/auth?access_token=")
				.append(requestUserModel.getAccessToken()).append("&openid=").append(requestUserModel.getOpenId());
			String json = HttpUtil.doGet(URL.toString()) ;
			WeChatTokenVo vo = JSONObject.parseObject(json, WeChatTokenVo.class);
		return new ResponseEntity<>(new ResponseResultModel<WeChatTokenVo>(vo), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("通过code换取网页授权access_token异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/**授权
	 *  
	 * 
	 * @param requestUserSet
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/authorization", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> authorization(@RequestBody RequestUserModel requestUserModel) {
		try {
			ResponseUnDefinedUserVo responseUnDefinedUserVo=new ResponseUnDefinedUserVo();
			if (requestUserModel.getCode()==null) {
				//必传参数未传
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK); 
			} 
			//获取token 第一步
			StringBuffer URL = new StringBuffer();
//			URL.append("https://api.weixin.qq.com/sns/oauth2/access_token?appid=")
//				.append("wx65d97c0cfa18b4f8").append("&secret=").append("07c5607f3fc4ca05812ff4c7a6289243")
//				.append("&code=").append(requestUserModel.getCode())
//				.append("&grant_type=authorization_code");
			URL.append("https://api.weixin.qq.com/sns/oauth2/access_token?appid=")
			.append(Config.getString("wechat.appId")).append("&secret=").append(Config.getString("wechat.secret"))
			.append("&code=").append(requestUserModel.getCode())
			.append("&grant_type=authorization_code");
//			logger.debug("请求微信的 URL --------->: {}", URL);
			String json = HttpUtil.doGet(URL.toString()) ;
//			logger.debug("微信的返回值-----------> :  {}", json);
			WeChatTokenVo vo = JSONObject.parseObject(json, WeChatTokenVo.class);
			if (vo.getAccess_token()==null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20146), HttpStatus.OK);	
			}
				//第二步 拉取用户信息
				StringBuffer URL1 = new StringBuffer() ;
				URL1.append("https://api.weixin.qq.com/sns/userinfo?access_token=")
					.append(vo.getAccess_token()).append("&openid=").append(vo.getOpenid())
					.append("&lang=zh_CN");
				String json1 = HttpUtil.doGet(URL1.toString()) ;
				WeChatUserInfoVo vo1 = JSONObject.parseObject(json1, WeChatUserInfoVo.class);
				//如果拉取失败就刷新
				if (vo1.getOpenid()==null) {
//					responseUnDefinedUserVo.setMsg("拉取用户信息失败 准备进行刷新。。。"+vo1.getErrmsg());
//					StringBuffer URL2 = new StringBuffer() ;
//					URL2.append("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=")
//						.append("wx65d97c0cfa18b4f8").append("&grant_type=REFRESH_TOKEN")
//						.append("&refresh_token=").append(vo.getRefresh_token());
//					String json2 = HttpUtil.doGet(URL2.toString()) ;
//					WeChatTokenVo vo2 = JSONObject.parseObject(json2, WeChatTokenVo.class);
//					if (vo2.getAccess_token()==null) {
//						//刷新再失败就没办法了 一边玩儿去
						return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20148), HttpStatus.OK);
				//	}
				}
				responseUnDefinedUserVo.setAccessToken(vo.getAccess_token());
				responseUnDefinedUserVo.setOpenid(vo.getOpenid());
				//responseUnDefinedUserVo.setRefreshToken(vo2.);
				responseUnDefinedUserVo.setNickName(vo1.getNickname());
				responseUnDefinedUserVo.setSex(vo1.getSex());
				responseUnDefinedUserVo.setProvince(vo1.getProvince());
				responseUnDefinedUserVo.setCity(vo1.getCity());
				responseUnDefinedUserVo.setCountry(vo1.getCountry());
				responseUnDefinedUserVo.setHeadimgurl(vo1.getHeadimgurl());
				responseUnDefinedUserVo.setUnionid(vo.getUnionid());
				responseUnDefinedUserVo.setRefreshToken(vo.getRefresh_token());
				return new ResponseEntity<>(new ResponseResultModel<ResponseUnDefinedUserVo>(responseUnDefinedUserVo), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("微信授权异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/**
	 *  验证
	 * 
	 * @param requestUserSet
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/geiPengHeYong", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> geiPengHeYong(@RequestBody RequestUserModel requestUserModel) {
		try {
			if (requestUserModel.getAccessToken()==null||requestUserModel.getOpenId()==null||requestUserModel.getRefreshToken()==null) {
				//必传参数未传
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK); 
			}
			StringBuffer URL = new StringBuffer();
			URL.append("https://api.weixin.qq.com/sns/auth?access_token=")
				.append(requestUserModel.getAccessToken()).append("&openid=").append(requestUserModel.getOpenId());
			String json = HttpUtil.doGet(URL.toString()) ;
			WeChatTokenVo vo = JSONObject.parseObject(json, WeChatTokenVo.class);
			if (vo.getAccess_token()==null) {
				StringBuffer URL2 = new StringBuffer() ;
//				URL2.append("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=")
//					.append("wx65d97c0cfa18b4f8").append("&grant_type=REFRESH_TOKEN")
//					.append("&refresh_token=").append(requestUserModel.getRefreshToken());
				URL2.append("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=")
				.append(Config.getString("wechat.appId")).append("&grant_type=REFRESH_TOKEN")
				.append("&refresh_token=").append(requestUserModel.getRefreshToken());
				String json2 = HttpUtil.doGet(URL2.toString()) ;
				WeChatTokenVo vo2 = JSONObject.parseObject(json2, WeChatTokenVo.class);
				return new ResponseEntity<>(new ResponseResultModel<WeChatTokenVo>(vo2), HttpStatus.OK);
			}
		return new ResponseEntity<>(new ResponseResultModel<WeChatTokenVo>(vo), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("通过code换取网页授权access_token异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/**
	* **********************************************
	* @Title: getWechatUserInfoByCode 
	* @Description: 根据微信Code返回小铺来了第三方微信用户信息
	* @param @param requestUserModel
	* @param @param request
	* @param @return 
	* @return ResponseEntity<?>
	* @throws	
	* @author NingChongQing	
	* @date 2017年12月21日 上午11:59:33 
	* **********************************************
	 */
	@ResponseBody
	@RequestMapping(value = "/getWechatUserInfoByCode", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getWechatUserInfoByCode(@RequestBody RequestUserModel requestUserModel,HttpServletRequest request) {
		try {
			if (requestUserModel.getCode()==null) {
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK); 
			} 
			String redisKey = StringUtils.EMPTY + requestUserModel.getCode();
			// 从Redis中读取缓存
			String authJson = queryCacheResult(redisKey);
			
			if(!StringUtils.isBlank(authJson)) {
				logger.error("redis 存在 TOKEN : {}",authJson);
			}else {
				logger.error("redis 不存在 TOKEN ");
			}
			
			// Redis没有缓存AccessToken
			if (StringUtils.isEmpty(authJson)) {
				// 获取token
				StringBuffer URL = new StringBuffer();
				URL.append("https://api.weixin.qq.com/sns/oauth2/access_token?appid=")
				.append(Config.getString("wechat.appId")).append("&secret=").append(Config.getString("wechat.secret"))
				.append("&code=").append(requestUserModel.getCode()).append("&grant_type=authorization_code");
				authJson = HttpUtil.doGet(URL.toString()) ;
				toCacheResult(redisKey, authJson, 5400);// 有效时间1小时30分钟
				
				logger.error("weixin return : {}  ---------  {} ", URL.toString() , authJson);
			}
			WeChatTokenVo vo = JSONObject.parseObject(authJson, WeChatTokenVo.class);
			if (vo.getAccess_token()==null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20146), HttpStatus.OK);	
			}
			// 拉取用户信息
			StringBuffer URL1 = new StringBuffer() ;
			URL1.append("https://api.weixin.qq.com/sns/userinfo?access_token=")
				.append(vo.getAccess_token()).append("&openid=").append(vo.getOpenid()).append("&lang=zh_CN");
			String wechatUserInfoJson = HttpUtil.doGet(URL1.toString()) ;
			WeChatUserInfoVo wechatUserInfo = JSONObject.parseObject(wechatUserInfoJson, WeChatUserInfoVo.class);
			// 如果拉取失败就刷新
			if (wechatUserInfo.getOpenid()==null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20148), HttpStatus.OK);
			}
			String clientType = ClientType.APP;
			if(request.getHeader("phoneType") != null && request.getHeader("phoneType").length() > 0) {
				if(request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_IOS) || request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_ANDROID)){
					clientType = ClientType.APP;
				} else if(request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_h5) || request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_WX)) {
					clientType = ClientType.H5;
				}
			}
			return this.undefinedUserService.getUndefinedUserByUndefinedId(wechatUserInfo.getOpenid(), wechatUserInfo.getNickname(),wechatUserInfo.getHeadimgurl(),clientType);
		} catch (Exception e) {
			logger.error("根据微信Code返回小铺来了第三方微信用户信息:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	/**
	* **********************************************
	* @Title: getWechatUserInfoByCodeForTest
	* @Description: 根据微信Code返回小铺来了第三方微信用户信息  应付测试
	* @param @param requestUserModel
	* @param @param request
	* @param @return
	* @return ResponseEntity<?>
	* @throws
	* @author NingChongQing
	* @date 2018年1月2日 下午2:53:27
	* **********************************************
	 */
	@ResponseBody
	@RequestMapping(value = "/getWechatUserInfoByCodeForTest", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getWechatUserInfoByCodeForTest(@RequestBody RequestUserModel requestUserModel,HttpServletRequest request) {
		try {
			if (requestUserModel.getCode()==null) {
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			Thread.sleep(1000);
			String clientType = ClientType.APP;
			return this.undefinedUserService.getUndefinedUserByUndefinedId("oEoT_wvENGozg6HncCO1AKo2na2Y", "愤怒的小鸟","",clientType);
		} catch (Exception e) {
			logger.error("根据微信Code返回小铺来了第三方微信用户信息:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	/**
	 * @Description: 微信小程序WechatMiniPrograms登录接口
	 * @Author: zhangrenjie
	 * @Date: 2018/1/25 11:25
	 *
	 */
	@ResponseBody
	@RequestMapping(value = "/getWechatMiniProgramsUserInfoByCode", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getWechatMiniProgramsUserInfoByCode(@RequestBody RequestUserModel requestUserModel,HttpServletRequest request) {
		try {
			if (requestUserModel.getCode()==null) {
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			//微信小程序登录token缓存key
			String redisKey_mini = getTempCacheKey(CommonConstants.WECHAT_MINI_PROGRAM,requestUserModel.getCode());
			String authJson_mini = queryCacheResult(redisKey_mini);
            if (StringUtils.isEmpty(authJson_mini)) {
                //调用微信小程序登录接口获取用户唯一标识openId
                //https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
                StringBuffer URL = new StringBuffer();
                URL.append("https://api.weixin.qq.com/sns/jscode2session?appid=")
						.append(Config.getString("wechat.mini.appId")).append("&secret=").append(Config.getString("wechat.mini.appSecret"))
						.append("&js_code=").append(requestUserModel.getCode()).append("&grant_type=authorization_code");
//				System.out.println(URL.toString()+"<<<<<<<<<<<<<<<<<<");
                authJson_mini = HttpUtil.doGet(URL.toString()) ;
                toCacheResult(redisKey_mini, authJson_mini, 5400);// 有效时间1小时30分钟
            }
            WeChatMiniProgramToken MiniProgramTokenVo = JSONObject.parseObject(authJson_mini, WeChatMiniProgramToken.class);
            if (MiniProgramTokenVo.getOpenid()==null) {
                return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20146), HttpStatus.OK);
            }
            /*//微信登录token缓存key
            String redisKey = getTempCacheKey(requestUserModel.getCode());
//            String redisKey = StringUtils.EMPTY + requestUserModel.getCode();
			String authJson = queryCacheResult(redisKey);
			//根据code获取Access_token
			if (StringUtils.isEmpty(authJson)) {
				StringBuffer URL = new StringBuffer();
				URL.append("https://api.weixin.qq.com/sns/oauth2/access_token?appid=")
						.append(Config.getString("wechat.appId")).append("&secret=").append(Config.getString("wechat.secret"))
						.append("&code=").append(requestUserModel.getCode()).append("&grant_type=authorization_code");
				authJson = HttpUtil.doGet(URL.toString()) ;
				toCacheResult(redisKey, authJson, 5400);// 有效时间1小时30分钟
			}
			WeChatTokenVo vo = JSONObject.parseObject(authJson, WeChatTokenVo.class);
			if (vo.getAccess_token()==null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20146), HttpStatus.OK);
			}
			// 拉取用户信息
			StringBuffer URL1 = new StringBuffer() ;
			URL1.append("https://api.weixin.qq.com/sns/userinfo?access_token=")
					.append(vo.getAccess_token()).append("&openid=").append(vo.getOpenid()).append("&lang=zh_CN");
			String wechatUserInfoJson = HttpUtil.doGet(URL1.toString()) ;
			WeChatUserInfoVo wechatUserInfo = JSONObject.parseObject(wechatUserInfoJson, WeChatUserInfoVo.class);

			//获取微信用户信息
			StringBuffer URL1 = new StringBuffer() ;
			URL1.append("https://api.weixin.qq.com/sns/userinfo?access_token=")
					.append(vo.getAccess_token()).append("&openid=").append(MiniProgramTokenVo.getOpenid()).append("&lang=zh_CN");
			String wechatUserInfoJson = HttpUtil.doGet(URL1.toString()) ;
			WeChatUserInfoVo wechatUserInfo = JSONObject.parseObject(wechatUserInfoJson, WeChatUserInfoVo.class);

			// 如果拉取失败就刷新
			if (wechatUserInfo.getOpenid()==null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20148), HttpStatus.OK);
			}*/
			String clientType = ClientType.APP;
			if(request.getHeader("phoneType") != null && request.getHeader("phoneType").length() > 0) {
				if(request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_IOS) || request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_ANDROID)){
					clientType = ClientType.APP;
				} else if(request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_h5) || request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_WX)) {
					clientType = ClientType.H5;
				}
			}
			return this.undefinedUserService.getUndefinedUserByUndefinedId(MiniProgramTokenVo.getOpenid(), requestUserModel.getNickName(),requestUserModel.getPicture(),clientType);
		} catch (Exception e) {
			logger.error("微信小程序登录接口返回小铺来了第三方微信用户信息:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
}
